package com.etc.api;

import com.etc.entity.SysUser;
import com.etc.service.SysUserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @Author kalista
 * @Description
 * @Date 2020/12/16  17:02
 **/
@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1. 获取用户名
        String username = req.getParameter("username");
        // 2. 获取密码
        String password = req.getParameter("password");
        // 3. 根据用户名查找用户
        SysUserService sysUserService = new SysUserService();
        //获取到数据库的用户
        SysUser login = sysUserService.login(username);
        if(login != null){
            if (login.getPassword().equals(password)){
                //创建seesion保持用户的登录状态
                HttpSession session = req.getSession();
                session.setAttribute("user",login);
                //请求转发
//                req.getRequestDispatcher("index").forward(req,resp);
                resp.sendRedirect("index");
            }else {
                req.setAttribute("message","密码错误");
                req.getRequestDispatcher("login.jsp").forward(req,resp);
            }
        }else {
            req.setAttribute("message","用户不存在");
            req.getRequestDispatcher("login.jsp").forward(req,resp);
        }


    }
}
